from scipy import load,mean, savez,array,isnan,ones,arange,unique,shape,nan,concatenate,nanmax,diff,copy,argmin,argmax,multiply,sum,ceil,floor,polyfit,nanargmin, roll, linspace,log10,nanmin,ceil
from matplotlib.mlab import find
from pylab import close,plot, xlabel, ylabel, imshow, gca, xlim, legend, figtext,figure,rcParams,clf,hist,imread,subplot,title,xscale,yscale,axes,draw

import tools.calc
from tools.plotroutines import *
def __main__(**kw):
  doReport(**kw)

def doReport(iv,icut=1,STDmax=0.05,FN_dV=0.02,dV=0.02,length=200,conf=.85,avgbias=1,nfitlength=9,force_diff=False,**kw):
    rcParams['axes.formatter.limits']=[-3,3]
    iv.Icut(icut1 = icut)
    dV = dV if dV>abs(iv.V[1]- iv.V[0])*5 else abs(iv.V[1]- iv.V[0])*5
    FN_dV = FN_dV if FN_dV > abs(iv.V[1]- iv.V[0])*5 else abs(iv.V[1]- iv.V[0])*5
    iv.correct_offset(dV)
    for i in range(2):
      if force_diff or len(array([iv.Imean[i][1]]).ravel()==1) or vars(iv).get('nfitlength',False)<>nfitlength:
        iv.numDI(nfitlength,mux=0)
    def doforeachgroup(func=lambda : nan):
      for i,group in enumerate(iv.Group):
        for FN in [True,False]:
          arg = tools.calc.intersect(iv.Group[group],find(iv.FN.FN_min_true==FN))
          func(arg,i=i,group=group,FN=FN)
    iv.groupIV()
    iv.stdIVs(STDmax)
    iv.FowlerNordheim(dV=FN_dV)
    iv.zerobiasconductance(dV)
    iv.histI(mux=0,length=length,conf=conf)
    traces = range(len(iv.Gfit))
    bins=10**linspace(floor(log10(nanmin(abs(iv.Gfit)))),ceil(log10(nanmax(iv.Gfit))),50)
    close(0);figure(0,figsize=(16,6))
    def fig0(arg,i,group,FN,**kw):
      plot(array(traces)[arg],iv.Gfit[arg],marker=('.' if group == 'linear' else ('+' if group == 'gap' else '^')),color=('red' if FN else 'blue'),ms=5,ls='None')
    doforeachgroup(fig0)
    yscale('log')
    mysavefig("results/%s/"% iv.basename,"report_%i" % (0));close(0)  
    def fig1(arg,i,group,FN,**kw):
      # low bias vs traces
      if FN and len(arg)>0:
        plot(iv.Gfit[arg],iv.FN.FN_min[arg,:],color='k',marker=('.' if group == 'linear' else ('+' if group == 'gap' else '^')),ms=5,ls='None')
    close(1);figure(1,figsize=(16,6))
    doforeachgroup(fig1)
    if len(find(iv.FN.FN_min_true==True))==0:
      clf();figtext(0.5,0.5,"No FN minima")
    else:
      xscale('log')
      legend([plot(nan,color='black',marker='+',ls='None',ms=5), plot(nan,color='black',marker='.',ls='None',ms=5), plot(nan,color='black',marker='^',ls='None',ms=5)],['gap', 'linear', 'zerobias enhancement'],loc='best')
      ylabel('FN minimum');xlabel('Low bias conductance $G/G_0$')
    mysavefig("results/%s/"% iv.basename,"report_%i" % (1));close(1)  
    def fig2(arg,i,group,FN,**kw):
      subplot(3,2,1+i*2+int(FN));iv.plot2Dgroup(arg,dI=0);title(group)
    close(2);figure(2,figsize=[ 12.65,  16.  ])
    doforeachgroup(fig2)
    mysavefig("results/%s/"% iv.basename,"report_%i" % (2));close(2) 
    def fig3(arg,i,group,FN,**kw):  
      subplot(3,2,1+i*2+int(FN));iv.plot2Dgroup(arg,dI=1);title(group)
    close(3);figure(3,figsize=[ 12.65,  16.  ])
    doforeachgroup(fig3)
    mysavefig("results/%s/"% iv.basename,"report_%i" % (3));close(3) 
    def fig4(arg,i,group,FN,**kw):
      subplot(3,2,1+i*2+int(FN));hist(iv.Gfit[arg],bins=bins);xlabel('Low bias conductance $G/G_0$');ylabel('Counts');xscale('log');xlim(min(bins),max(bins));title(group)
      box = gca().get_position ().get_points (); g=box[0,:]+(box[1,:]-box[0,:])/2.
      figtext(g[0],g[1],"%s" % len(arg))
    close(4);figure(4,figsize=[ 12.65,  16.  ])
    doforeachgroup(fig4)
    mysavefig("results/%s/"% iv.basename,"report_%i" % (4));close(4) 
    def fig10a(arg,i,group,FN,**kw):
      figure(10,figsize=(6,8));clf();iv.plot2Dgroup(arg,dI=0);
      mysavefig("results/%s/"% iv.basename,"report_%i_%s_%s" % (2,group,'FN' if FN else 'noFN'));close(10)
    def fig10b(arg,i,group,FN,**kw):
      figure(10,figsize=(6,8));clf();iv.plot2Dgroup(arg,dI=1);
      mysavefig("results/%s/"% iv.basename,"report_%i_%s_%s" % (3,group,'FN' if FN else 'noFN'));close(10)
    doforeachgroup(fig10a)  
    doforeachgroup(fig10b)  
    FNmin = iv.FN.FN_min[isnan(iv.FN.FN_min.sum(1))==False,:].ravel()
    FNmin = FNmin[isnan(FNmin)==False]
    close(5);figure(5,figsize=[ 8,  6.  ]);clf() #hist FNvals
    if len(FNmin)>0:
      hist(FNmin,bins=linspace(nanmin(FNmin),nanmax(FNmin),50));xlim(nanmin(FNmin),nanmax(FNmin));ylabel('Counts');xlabel('FN minimum \'V\'')
    mysavefig("results/%s/"% iv.basename,"report_%i" % (5));close(5)
    close(6);figure(6,figsize=[ 8,  6.  ]);clf() #hist lowbias
    hist(iv.Gfit,bins=bins);xscale('log');xlim(min(bins),max(bins));xlabel('Low bias conductance $G/G_0$');ylabel('Counts')
    legend([plot(nan,color='black',marker='+',ls='None',ms=5), plot(nan,color='black',marker='.',ls='None',ms=5), plot(nan,color='black',marker='^',ls='None',ms=5),        plot(nan,color='red',marker='o',ls='None',ms=5),  plot(nan,color='blue',marker='o',ls='None',ms=5)],['gap', 'linear', 'zerobias enhancement','FN','no FN'],loc='best')
    xlabel('Traces');ylabel('Low bias conductance $G/G_0$')
    mysavefig("results/%s/"% iv.basename,"report_%i" % (6));close(6)
    def plotim(imfile):
      A=imread(imfile)
      imshow(A);gca().xaxis.set_visible (False);gca().yaxis.set_visible (False);draw()
    PlotIM  = lambda i: plotim("results/%s/report_%s.png" % (iv.basename,i))
    figure(11,figsize=[ 14.8125,  17.625 ]);clf();
    axes([0,.685, 1,.315]);PlotIM(0)
    axes([0, .37, 1,.315]);PlotIM(1)
    axes([0,  .0,.5,.37]);PlotIM(5)
    axes([0.5,.0,.5,.37]);PlotIM(6)
    mysavefig("results/%s/"% iv.basename,"report_%i" % (11));close(11)

